<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>站点拥挤度分析 - Apache ECharts</title>
    <link rel="stylesheet" href="css/style.css?v=1.1">
</head>

<body>
    <div class="navbar">
        <a href="index.html">首页</a>
        <a href="traffic_trend.html">客流趋势分析</a>
        <a href="station_ranking.html">站点客流排行</a>
        <a href="funnel_analysis.html">线路站点客流分析</a>
        <a href="line_comparison.html">线路客流量对比</a>
        <a href="transfer_heatmap.html">换乘热度分析</a>
        <a href="poi_analysis.html">站点周边客流特征</a>
        <a href="anomaly_detection.html">异常客流检测</a>
        <a href="od_analysis.html">路径OD分析</a>
        <a href="stop_frequency_usage_analysis.html">站停频率分析</a>
        <a href="dispatch_suggestion.html">智能调度模型</a>
    </div>
    <div class="page-container">
        <div class="chart-header">
            <h2 class="chart-title">站点拥挤度分析</h2>
            <p class="chart-description">
                此图通过气泡的大小直观展示了各个站点的平均拥挤程度。气泡越大，代表该站点的客流压力越大。通过此分析，可以快速识别出关键拥挤站点，为运力调度、客流疏导等提供决策支持。
            </p>
        </div>
        <div class="kpi-cards-container">
            <div class="kpi-card">
                <h4>最拥挤站点</h4>
                <p id="top-crowded-station">--</p>
            </div>
            <div class="kpi-card">
                <h4>最不拥挤站点</h4>
                <p id="least-crowded-station">--</p>
            </div>
            <div class="kpi-card">
                <h4>平均拥挤指数</h4>
                <p id="average-crowd">--</p>
            </div>
            <div class="kpi-card">
                <h4>分析站点总数</h4>
                <p id="total-stations-crowd">--</p>
            </div>
        </div>
        <div id="crowd-chart-container" class="chart-container"></div>
    </div>

    <div id="main" style="width: 100%; height:800px;"></div>

    <script src="js/echarts.min.js"></script>
    <script type="text/javascript">
        var crowdChart = echarts.init(document.getElementById('crowd-chart-container'));

        fetch('/api/subway/peak_crowd_ranking')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {

                const filteredData = data.filter(item => item.avgCrowdLevel > 0);

                const chartData = filteredData.map(item => ({
                    name: item.stationName,
                    value: item.avgCrowdLevel
                }));

                // --- KPI Card Calculations for Crowd Analysis ---
                if (chartData.length > 0) {
                    // Sort by crowd level
                    const sortedData = [...chartData].sort((a, b) => b.value - a.value);

                    // 1. Most Crowded Station
                    const topStation = sortedData[0];
                    document.getElementById('top-crowded-station').innerHTML = `${topStation.name}<br><small style="font-size: 0.5em;">${topStation.value.toFixed(2)}</small>`;

                    // 2. Least Crowded Station
                    const leastStation = sortedData[sortedData.length - 1];
                    document.getElementById('least-crowded-station').innerHTML = `${leastStation.name}<br><small style="font-size: 0.5em;">${leastStation.value.toFixed(2)}</small>`;

                    // 3. Average Crowd Level
                    const totalCrowd = chartData.reduce((sum, item) => sum + item.value, 0);
                    const avgCrowd = totalCrowd / chartData.length;
                    document.getElementById('average-crowd').innerText = avgCrowd.toFixed(2);

                    // 4. Total Stations Analyzed
                    document.getElementById('total-stations-crowd').innerText = chartData.length;
                }
                // --- End of KPI Card Calculations ---

                if (chartData.length === 0) {
                    document.getElementById('crowd-chart-container').innerText = '暂无有效数据显示';
                    return;
                }

                const minVal = Math.min(...chartData.map(item => item.value));
                const maxVal = Math.max(...chartData.map(item => item.value));

                var option = {
                    title: {
                        text: '站点拥挤度分析（力引导布局）',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: function (params) {
                            if (params.dataType === 'node') {
                                return params.name + '<br/>拥挤度: ' + params.value.toFixed(3);
                            }
                        }
                    },
                    visualMap: {
                        show: true,
                        min: minVal,
                        max: maxVal,
                        inRange: {
                            color: ['#CDE4FF', '#5A94EB', '#254E8C'], // A nicer blue color scheme
                            symbolSize: [20, 80] // Map value to bubble size
                        },
                        calculable: true,
                        orient: 'horizontal',
                        left: 'center',
                        bottom: '10%'
                    },
                    series: [{
                        type: 'graph',
                        layout: 'force',
                        force: {
                            repulsion: 100,
                            gravity: 0.1,
                            edgeLength: 30
                        },
                        roam: true, // Allow zooming and panning
                        data: chartData,
                        label: {
                            show: true,
                            position: 'inside',
                            formatter: '{b}',
                            color: '#fff',
                            fontSize: 12,
                            textShadowBlur: 2,
                            textShadowColor: 'rgba(0, 0, 0, 0.3)'
                        },
                        itemStyle: {
                            shadowBlur: 10,
                            shadowColor: 'rgba(0, 0, 0, 0.3)',
                            shadowOffsetY: 3
                        }
                    }]
                };
                crowdChart.setOption(option);
            })
            .catch(error => {
                console.error('获取站点拥挤度数据失败:', error);
                document.getElementById('crowd-chart-container').innerText = '数据加载失败，请检查后端服务或网络连接。';
            });

        window.addEventListener('resize', function () {
            if (crowdChart) {
                crowdChart.resize();
            }
        });
    </script>
    <script src="js/common.js"></script>
</body>

</html>